package ocp.management;

/*
 *  Gesti&oaqute;
 * 15 october of 2008 
 */
import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.ModelRDB;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.shared.AlreadyExistsException;

import java.util.Arrays;
/*
import org.mindswap.pellet.jena.PelletReasonerFactory;
import org.umu.ore.data.RuleCollection;
import org.umu.ore.data.XMLSerializationException;
import org.umu.ore.util.OntologyManager;
 */
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import ocp.context.Context;
/*
import org.mindswap.pellet.jena.PelletReasonerFactory;
import org.umu.ore.data.RuleCollection;
import org.umu.ore.data.XMLSerializationException;
import org.umu.ore.util.OntologyManager;
 */
import ocp.context.ContextException;
import ocp.service.Interval;
import ocp.util.Log;

public class OntologyManagement {

//    private static final String CONFIG_FILE = "/resources/config.ini";
    protected String modelContextName;    // ontological model name

    protected String modelContextFile;
    protected IDBConnection connection;   // connection with the database

    protected String dbDriver;
    protected String dbUrl;
    protected String dbUser;
    protected String dbPassword;
    protected String dbName; // database parameters
    
    private boolean resetJenaDB = false;

    protected OntModel model; // ontological model.
    //protected IUniqueIDGenerator idGenerator; // Unique ID Generator for new contexts.

    protected JenaToContextTranslator j2ct;
    protected ContextToJenaTranslator c2jt;
    private static OntologyManagement instance;
    private OntModel pelletModel;
    
    /**
     * Creates a new instance of OntologyManagement
     */
    private OntologyManagement(String dbDriver , String dbUrl , String dbUser , String dbPassword , String dbName) throws Exception {

        modelContextName = "ocp";
        //modelContextName = "file://eu/popeye/resources/context.owl#";
        
        modelContextFile = "Context.owl";
        
        resetJenaDB = true; //%%% de momento creo una db cada vez que arranco
        
        // Se lee el fichero de configuracion
        //readConfig();
        this.dbDriver = dbDriver;
        this.dbUrl = dbUrl;
        this.dbUser = dbUser;
        this.dbPassword = dbPassword;
        this.dbName = dbName;
        
        
        // Se crea la conexion a la base de datos
        Class.forName(dbDriver);
        connection = new DBConnection(dbUrl, dbUser, dbPassword, dbName);
        
        // borra el contenido de la db
        if( resetJenaDB ) connection.cleanDB();

        // Se crea el modelo en la ontologia
        // loadRules();
        // prepareImports();
        createOntology();      
        prepareModel();
        //  idGenerator = new SimpleUniqueIDGenerator();
        //  idGenerator.initialize();

        j2ct = new JenaToContextTranslator(model);
        c2jt = new ContextToJenaTranslator(model);
    }


    public static OntologyManagement getInstance(String dbDriver , String dbUrl , String dbUser , String dbPassword , String dbName) throws Exception {
        if (instance == null) {
            instance = new OntologyManagement(dbDriver , dbUrl , dbUser , dbPassword , dbName);
        }
        return instance;
    }

    public int getCountHistorical(String id) {
        try {
            return j2ct.getCountHistorical(id);
        } catch (ContextException ex) {
            return 0;
        }
    }
    
    

    /**
     * Lee un contexto de la ontologia
     * @param id
     * @return null si no ha podido leer el contexto
     */
    public Context readContext(String id) {
        try  {
            return j2ct.getContext(id);
        }
        catch(ContextException c)  {
            //c.printStackTrace();
            Log.logError( "Error leyendo contexto [" + id + "]" , c );
        }
        return null;
    }
    
    public class ComparadorContexto implements Comparator<Context> 
    {
        public int compare(Context o1, Context o2) {
            String id1 = o1.getId();
            String id2 = o2.getId();
            return id1.compareTo(id2);
        }
        
/*
   String instant = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(calendar.getTime());
        String newContext = c.getName() + "|" + instant;
 */        
    }

    public Vector<Context> readHistoricalContextLast(String id, int nitems)  {
        
        try {
            Vector<Context> res;
            int n;

                
            Interval interval = j2ct.getHistoricalInterval(id);
            Vector<Context> hContext = j2ct.getHContext(id, interval.getBegin(), interval.getEnd());
            n = hContext.size();
            if( nitems > n ) 
                return null;
            List<Context> lista = hContext.subList(0, n );
            java.util.Collections.sort(lista , new ComparadorContexto());
            
            // Cojo los últimos elementos
            res = new Vector<Context>( lista.subList( n - nitems , n ) );
            return res;
            
        } catch (ContextException ex) {
            Log.logError( "readHistoricalContextLast(): Error leyendo historico de contexto [" + id + "]" , ex );
            return null;
        }
        
    }

    /**
     * Escribe un contexto en la bbdd
     * @param context
     * @return true si el contexto es nuevo
     */
    public boolean writeContext(Context context) {
        boolean nuevo;
        try  {
            nuevo = !j2ct.containsContext( context.getId() );
            c2jt.addContext(context);
            return nuevo;  
        }
        catch(ContextException c)  {
            //c.printStackTrace();
            Log.logError( "Error escribiendo contexto [" + context.getId() + "]" , c );
        }
        return false;
    }

    private void createOntology() {
        try {
            
                    
            // Creamos la ontologia del Contexto y el modelo
            ModelRDB modelo = ModelRDB.createModel(connection, modelContextName);
            
            Log.logInfo( "Model URL:[" + getClass().getResource(modelContextFile).toString() + "]");
                    
            // add xml file to model        
            modelo.read( getClass().getResource(modelContextFile).toString() );
            modelo.setDoDuplicateCheck(false);
            
            OntModel ontmodel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, modelo);
            ontmodel.setDynamicImports(true);

            if (ontmodel != null) {
                Log.logInfo("Ontology successfuly created.");
            } else {
                Log.logError("Failed to create the Ontology.");
                System.exit(-2);  //TODO
            }

        } catch (AlreadyExistsException ae) {
            Log.logError("Ontology Already Exists");
        } catch (Exception e) {
            Log.logError( "createOntology: Exception" , e);
            
            e.printStackTrace();
        }

    }

    /**
     * Reads the configuration file containing the database parameters and the
     * model name.
     */
    public void readConfig() throws Exception {
        /*
        Properties properties = new Properties();
        
        File archivo = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
        String path = archivo.getAbsolutePath();
        
        
        InputStreamReader fis = new InputStreamReader(this.getClass().getResourceAsStream(CONFIG_FILE));
        properties.load(fis);
        fis.close();
        
        dbDriver = properties.getProperty("DB_DRIVER");
        dbUrl = properties.getProperty("DB_URL");
        dbUser = properties.getProperty("DB_USER");
        dbPassword = properties.getProperty("DB_PASSWORD");
        dbName = properties.getProperty("DB_NAME");
         */
    }

    /**
     * Load rules form Reasoner and Metareasoner
     */
//    private void loadRules() {
//        try {
//
//            BuiltinRegistry.theRegistry.register(new DeleteProperty());
//            BuiltinRegistry.theRegistry.register(new DeletePropertyValue());
//            BuiltinRegistry.theRegistry.register(new NoConnection());
//
//            org.umu.ore.util.Constants.DEBUG = "ON";
//
//            OntologyManager.initBaseOntologyModel(getClass().getResource(rulesProDiaFile).toString());
//            rulesProDia = RuleCollection.getRuleCollection().toGRT();
//
//            RuleCollection.getRuleCollection().getRules().clear();
//
//            OntologyManager.initBaseOntologyModel(getClass().getResource(metaRulesProDiaFile).toString());
//            metaRulesProDia = RuleCollection.getRuleCollection().toGRT();
//
//            RuleCollection.getRuleCollection().getRules().clear();
//
//        } catch (XMLSerializationException ex) {
//            ex.printStackTrace();
//            Logger.getLogger(OntologyManagement.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//
//    }
    
public OntModelSpec getModelSpec( ModelMaker maker ) {
        // create a spec for the new ont model that will use no inference over models
        // made by the given maker (which is where we get the persistent models from)
        OntModelSpec spec = new OntModelSpec( OntModelSpec.OWL_MEM );
        spec.setImportModelMaker( maker );

        return spec;
    }
    
    /**
     * This method creates the Document Manager and the connections to the
     * ontological models.
     */
    public void prepareModel() {
        
        ModelMaker maker = ModelFactory.createModelRDBMaker( connection );
        
        // use the model maker to get the base model as a persistent model
        // strict=false, so we get an existing model by that name if it exists
        // or create a new one
        Model base = maker.createModel( modelContextName, false );

        // create an ontology model using the persistent model as base
        OntModel m = ModelFactory.createOntologyModel( getModelSpec( maker ), base );

        // ejemplo iterador de clases 
        /*
        for (Iterator i = m.listClasses(); i.hasNext(); ) {
            OntClass c = (OntClass) i.next();
         
            System.out.println( "Class " + c.getURI() );
        }
        */

        model = m;
        Log.logInfo( "Modelo cargado." );
        
        
        /*
        System.out.println("Cargando modelo.....");
        ControllerView.getInstance().appendLog("Cargando Modelo...");
        
        //   ModelRDB modelRDB = ModelRDB.open(connection, modelContextName);
        //  modelRDB.setDoDuplicateCheck(true);
        model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        model.read(getClass().getResource(modelContextFile).toString());
        
        
        // Creamos la ontologia del Contexto y el modelo
        //   ModelRDB modelPro = ModelRDB.createModel(connection, modelProDiaName);
        modelProDia = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        //      modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/geo-measurement");
        modelProDia.read(getClass().getResource(modelGeoFile).toString());
        //    modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/space");
        modelProDia.read(getClass().getResource(modelSpaceFile).toString());
        //  modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/policy");
        modelProDia.read(getClass().getResource(modelPolicyFile).toString());
        //modelPro.read("http://pervasive.semanticweb.org/ont/2004/01/time");
        modelProDia.read(getClass().getResource(modelTimeFile).toString());
        //modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/person");
        modelProDia.read(getClass().getResource(modelPersonFile).toString());
        //modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/action");
        modelProDia.read(getClass().getResource(modelActionFile).toString());
        //modelPro.read("http://pervasive.semanticweb.org/ont/2004/06/rcc");
        modelProDia.read(getClass().getResource(modelRCCFile).toString());
        //modelPro.read("http://www.owl.ontologies.es/unnamed.owl");
        modelProDia.read(getClass().getResource(modelBuildingFile).toString());
        modelProDia.read(getClass().getResource(modelProDiaFile).toString());
        //   modelProDia.setDoDuplicateCheck(false);
        //    OntModel ontmodel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, modelPro);
        modelProDia.setDynamicImports(true);
        
        if (modelProDia != null) {
        System.out.println("Ontology successfuly created.");
        } else {
        System.err.println("Failed to create the Ontology.");
        System.exit(-2);
        }
        
        
        
        
        System.out.println("Modelo cargado");
        ControllerView.getInstance().appendLog("Modelo Cargado");
        
         */
    }

    /*
    private void prepareImports() {
    
    OntDocumentManager dm = OntDocumentManager.getInstance(); //policyUri);
    
    dm.addIgnoreImport("http://pervasive.semanticweb.org/ont/2004/06/space");
    dm.addIgnoreImport("http://pervasive.semanticweb.org/ont/2004/01/time");
    dm.addIgnoreImport("http://pervasive.semanticweb.org/ont/2004/06/time");
    dm.addIgnoreImport("http://pervasive.semanticweb.org/ont/2004/06/policy");
    dm.addIgnoreImport("http://pervasive.semanticweb.org/ont/2004/06/action");
    
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/geo-measurement", getClass().getResource(modelGeoFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/space", getClass().getResource(modelSpaceFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/policy", getClass().getResource(modelPolicyFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/01/time", getClass().getResource(modelTimeFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/person", getClass().getResource(modelPersonFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/action", getClass().getResource(modelActionFile).toString());
    dm.addAltEntry("http://pervasive.semanticweb.org/ont/2004/06/rcc", getClass().getResource(modelRCCFile).toString());
    dm.addAltEntry("http://www.owl.ontologies.es/unnamed.owl", getClass().getResource(modelBuildingFile).toString());
    dm.addAltEntry("http://www.owl.ontologies.com/ProDia.owl", getClass().getResource(modelProDiaFile).toString());
    
    
    
    }
     * */
    /*
     * 
     * 
    public synchronized void reset() {
    try {
    
    // Se lee el fichero de configuracion
    readConfig();
    //Nuevo modelo de razonamiento
    Class.forName(dbDriver);
    connection = new DBConnection(dbUrl, dbUser, dbPassword, dbName);
    // Se crea el modelo en la ontologia
    loadRules();
    prepareImports();
    createOntology();
    prepareModel();
    idGenerator = new SimpleUniqueIDGenerator();
    idGenerator.initialize();
    j2ct = new JenaToContextTranslator(model);
    c2jt = new ContextToJenaTranslator(model, modelProDia, timersProperties);
    
    listeners = new ArrayList<OntologyListener>();
    
    pelletModel = null; //Nuevo modelo de razonamiento
    
    modeInit = true;
    } catch (Exception ex) {
    ex.printStackTrace();
    Logger.getLogger(OntologyManagement.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    }
    
    public synchronized void register(RegistrationTuple template, LindaEntryListener listener) {
    LindaEntry result = getLindaEntry(template.getContextName());
    if (result == null) {
    result = new LindaEntry(modelContextName, template.getContextName());
    result.register(template.space, listener);
    listenedEntries.add(result);
    } else {
    result.register(template.space, listener);
    }
    if (result.hasValue()) {
    result.update_listener(listener, listener.getConnection());
    }
    System.err.println(listener.getConnection() + " registered as listener of context " + template.getContextName());
    }
    
    public synchronized void unregister(DeregistrationTuple template, LindaEntryListener listener) {
    LindaEntry result = getLindaEntry(template.getContextName());
    if (result != null) {
    result.unregister(template.space, listener);
    System.err.println(listener.getConnection() + " deregistered as listener of context " + template.getContextName());
    }
    }
    
    //  busca una linda entry que coincida con una tupla. 
    public LindaEntry getLindaEntry(String key) {
    for (Enumeration e = listenedEntries.elements(); e.hasMoreElements();) {
    LindaEntry l = (LindaEntry) e.nextElement();
    if (l.key().equals(key)) {
    return l;
    }
    }
    return null;
    }
    
    private Tuple readHistoricalContext(HistoricalContextRequestTuple template) throws ContextualInformationAbsentException {
    try {
    Vector contexts = j2ct.getHContext(template.getContextName(), template.getBeginInterval(), template.getEndInterval());
    HistoricalContextTuple tuple = null;
    if (contexts != null) {
    tuple = new HistoricalContextTuple(template.getContextName(), new HistoricalItem(contexts));
    }
    return tuple;
    } catch (ContextualException ex) {
    ex.printStackTrace();
    return new HistoricalContextTuple(template.getContextName(), new HistoricalItem(null));
    }
    }
    
    private Tuple readContext(ContextRequestTuple template) {
    String uriSubject = template.getContextName();
    ContextualItem ci;
    Context c = null;////////////////////////////////////////////////////////////////////////////////////////////////////
    int tries = 0;
    int MAX_TRIES = 3;
    try {
    while ((c == null) && (tries < MAX_TRIES)) {
    c = j2ct.getContext(uriSubject);
    tries++;
    }
    ci = new ContextualItem(c);
    } catch (ContextualException e) {
    System.err.println("Error obtaining context " + uriSubject);
    ci = new ContextualItem(null);
    }
    return new Tuple(uriSubject, ci);
    }
    
    private Tuple countHistorical(CountRequestTuple template) {
    try {
    String contextName = template.getContextName();
    int i = j2ct.getCountHistorical(contextName);
    return new CountTuple(contextName, new CountItem(contextName, i));
    } catch (ContextualException ex) {
    return new CountTuple(template.getContextName(), new CountItem(null));
    }
    }
    
    private Tuple readHistoricalByIndexContext(SingleHistoricalRequestTuple template) {
    try {
    String contextName = template.getContextName();
    int index = template.getIndex();
    Context c = j2ct.getHistoricalByIndex(contextName, index);
    return new SingleHistoricalTuple(contextName, new SingleHistoricalItem(c));
    } catch (ContextualException ex) {
    ex.printStackTrace();
    return new SingleHistoricalTuple(template.getContextName(), new SingleHistoricalItem(null));
    }
    }
    
    private Tuple historicalInterval(IntervalRequestTuple template) {
    try {
    String contextName = template.getContextName();
    Interval interval = j2ct.getHistoricalInterval(contextName);
    return new IntervalTuple(contextName, new IntervalItem(interval));
    } catch (ContextualException ex) {
    ex.printStackTrace();
    //            Logger.getLogger(ContextualProdiaSpace.class.getName()).log(Level.SEVERE, null, ex);
    return new IntervalTuple(template.getContextName(), new IntervalItem(null));
    }
    }
    
    // writes a tuple in the space. 
    public synchronized boolean write(RequestTuple template, LindaConnection connection) {
    // Send the tuple to the receiver.
    Tuple tuple = null;
    try {
    if (template instanceof CommandTuple) {
    } else if (template instanceof ContextStoreTuple) {
    Context c = ((ContextStoreTuple) template).getContext();
    if (c == null) {
    return false;
    }
    c2jt.addContext(c);
    LindaEntry le = getLindaEntry(((ContextStoreTuple) template).getContext().getName());
    if (le != null) {
    le.update_local(template);
    le.update_listeners(connection);
    }
    return true;
    }
    } catch (ContextualException ce) {
    ce.printStackTrace();
    // aborta la transacción si hay alguna en curso
    model.abort();
    } catch (RuntimeException e) {
    e.printStackTrace();
    // aborta la transaccion si hay alguna en curso
    model.abort();
    throw e;
    }
    return false;
    }
    
    private String getStringToNode(RDFNode node) {
    if (node == null) {
    return "null";
    } else if (node.isLiteral()) {
    Literal l = (Literal) node;
    return l.getString();
    } else if (node.isResource()) {
    Resource l = (Resource) node;
    return l.getLocalName();
    }
    return node.toString();
    }
    
    private String getProperty(String id, String nameProperty, int type) {
    
    Individual individuo = modelProDia.getIndividual(Constants.PREFIX + id);
    if (individuo == null) {
    throw new RuntimeException("Instance : " + id + " not found");
    }
    Property property = null;
    if (type == Constants.TYPEDATAPROPERTY) {
    property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    } else if (type == Constants.TYPEOBJECTPROPERTY) {
    property = modelProDia.getObjectProperty(Constants.PREFIX + nameProperty);
    }
    if (property == null) {
    throw new RuntimeException("Property : " + nameProperty + " not found");
    }
    return getStringToNode(individuo.getPropertyValue(property));
    
    
    }
    
    public String getIdAttend(String typeAttend) {
    
    Resource r = modelProDia.getResource(Constants.PREFIX + typeAttend);
    
    for (Iterator it = modelProDia.listIndividuals(r); it.hasNext();) {
    Individual individuo = (Individual) it.next();           return individuo.getLocalName();
    }
    throw new RuntimeException("Attend not found");
    
    }
    
    public String getIdTimer(String type, String state) {
    
    Individual individual = modelProDia.getIndividual(Constants.PREFIX + type + state);
    if (individual != null) {
    return individual.getLocalName();
    //   System.out.println("No encontrado timer!!!!!");
    }
    return null;
    }
    
    public String getIdTimerSleepRest(String type, String state, String momentDay) {
    
    Individual individual = modelProDia.getIndividual(Constants.PREFIX + momentDay + type + state);
    if (individual != null) {
    return individual.getLocalName();
    //     System.out.println("No encontrado timer!!!!!");
    }
    return null;
    }
    
    public String getIdTimer(String type, String location, String momentDay) {
    
    Resource r = modelProDia.getResource(Constants.PREFIX + type);
    for (Iterator it = modelProDia.listIndividuals(r); it.hasNext();) {
    Individual individuo = (Individual) it.next();
    String sLocation = getProperty(individuo.getLocalName(), "locationTimer", Constants.TYPEOBJECTPROPERTY);
    String sMomentDay = getProperty(individuo.getLocalName(), "momentDayTimer", Constants.TYPEDATAPROPERTY);
    
    if (sLocation.equals(location) && sMomentDay.equals(momentDay)) {
    return individuo.getLocalName();
    } //Encontrado timer con caracteristicas
    
    }
    
    //System.out.println("No encontrado timer!!!!!");
    return null; //no encontrado
    
    
    }
    
    public String getIdTimerbyType(String type) {
    
    Resource r = modelProDia.getResource(Constants.PREFIX + type);
    List timers = modelProDia.listIndividuals(r).toList(); //solo hay uno
    
    Individual individuo = (Individual) timers.get(0);
    return individuo.getLocalName();
    
    }
    
    private void changeProperty(String id, String nameProperty, int type, RDFNode newValue) {
    //Cambiamos el valor de stateAttend por el newState inferido
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = null;
    if (type == Constants.TYPEDATAPROPERTY) {
    property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    }
    if (type == Constants.TYPEOBJECTPROPERTY) {
    property = modelProDia.getObjectProperty(Constants.PREFIX + nameProperty);
    }
    r.setPropertyValue(property, newValue);
    }
    
    public void changeState(String id, String newState) {
    //Cambiamos el valor de stateAttend por el newState inferido
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = modelProDia.getDatatypeProperty(Constants.PREFIX + STATEATTEND);
    Literal literal = modelProDia.createTypedLiteral(newState, XSDDatatype.XSDstring);
    r.setPropertyValue(property, literal);
    //Borramos el contenido de newState para la siguiente inferencia
    //      System.out.println("Cambiando estado atendido " + id + " y nuevo estado " + newState + " r es " + r + "property es " + property + " literal es " + literal);
    deleteProperty(id, NEWSTATEATTEND, Constants.TYPEDATAPROPERTY);
    }
    
    public void changeLocation(String id, Resource location) {
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = modelProDia.getObjectProperty(Constants.PREFIX + LOCATIONATTEND);
    r.setPropertyValue(property, location);
    //Borramos el contenido de newLocation para la siguiente inferencia
    deleteProperty(id, NEWLOCATIONATTEND, Constants.TYPEOBJECTPROPERTY);
    }
    
    private void deleteProperty(String id, String nameProperty, int type) {
    //Cambiamos el valor de stateAttend por el newState inferido
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = null;
    if (type == Constants.TYPEDATAPROPERTY) {
    property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    }
    if (type == Constants.TYPEOBJECTPROPERTY) {
    property = modelProDia.getObjectProperty(Constants.PREFIX + nameProperty);
    }
    r.removeAll(property);
    
    
    }
    
    private void deletePropertyValue(String id, String nameProperty, int type, String value) {
    
    //Cambiamos el valor de stateAttend por el newState inferido
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = null;
    if (type == Constants.TYPEDATAPROPERTY) {
    property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    }
    if (type == Constants.TYPEOBJECTPROPERTY) {
    property = modelProDia.getObjectProperty(Constants.PREFIX + nameProperty);
    }
    
    RDFNode aux = modelProDia.getResource(Constants.PREFIX + value);
    if (aux == null) {
    throw new RuntimeException("Resource " + value + " not found");
    }
    r.removeProperty(property, aux);
    
    
    }
    
    private void deleteLiteralPropertyValue(String id, String nameProperty, String value) {
    
    //Cambiamos el valor de stateAttend por el newState inferido
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    
    RDFNode aux = null;
    if (!r.listPropertyValues(property).toList().isEmpty()) {
    for (NodeIterator it = r.listPropertyValues(property); it.hasNext();) {
    LiteralImpl s = (LiteralImpl) it.next();
    if (s.getString().equals(value)) {
    aux = (RDFNode) s;
    }
    }
    if (aux != null) {
    r.removeProperty(property, aux);
    }
    }
    }
    
    public synchronized boolean notAdyancent(String id1, String id2) {
    
    Individual individuo = modelProDia.getIndividual(Constants.PREFIX + id1);
    Property property = modelProDia.getObjectProperty("http://www.owl.ontologies.es/unnamed.owl#haveConnection");
    
    
    for (Iterator it = individuo.listProperties(property); it.hasNext();) {
    
    StatementImpl s = (StatementImpl) it.next();
    
    //Tenemos una de las conexiones de la habitación1
    Resource r = s.getResource();
    Property proCon = modelProDia.getObjectProperty("http://www.owl.ontologies.es/unnamed.owl#ConnectionWith");
    
    for (Iterator it2 = r.listProperties(proCon); it2.hasNext();) {
    StatementImpl s2 = (StatementImpl) it2.next();
    //Tenemos las habitaciones de la conexion de la habitacion1
    
    Resource r2 = s2.getResource();
    
    if (r2.getLocalName().equals(id2)) {
    return false;
    }
    
    }
    }
    
    return true;
    }
    
    
    private void addStringProperty(String id, String nameProperty, String newValue) {
    OntResource r = modelProDia.getOntResource(Constants.PREFIX + id);
    Property property = modelProDia.getDatatypeProperty(Constants.PREFIX + nameProperty);
    Literal literal = modelProDia.createTypedLiteral(newValue, XSDDatatype.XSDstring);
    r.addProperty(property, literal);
    }
    
     */
}